package com.example.controller;

import com.example.entity.Group;
import com.example.mapper.GroupMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/groups")
public class GroupController {

    @Autowired
    private GroupMapper groupMapper;

    /**
     * 获取所有小组列表
     */
    @GetMapping
    public Map<String, Object> getAllGroups() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Group> groups = groupMapper.getAllGroups();
            result.put("code", "200");
            result.put("msg", "获取小组列表成功");
            result.put("data", groups);
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "获取小组列表失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据小组ID获取小组信息
     */
    @GetMapping("/{groupId}")
    public Map<String, Object> getGroupById(@PathVariable Integer groupId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Group group = groupMapper.getGroupById(groupId);
            result.put("code", "200");
            result.put("msg", "获取小组信息成功");
            result.put("data", group);
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "获取小组信息失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 检查用户是否已为项目负责人
     */
    @GetMapping("/checkLeader")
    public Map<String, Object> checkLeader(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户是否已经是小组组长
            List<Group> groups = groupMapper.getAllGroups();
            boolean isLeader = groups.stream()
                .anyMatch(group -> group.getLeader().equals(username));
            
            result.put("code", "200");
            result.put("msg", "操作成功");
            result.put("data", isLeader);
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "检查负责人失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 创建新小组
     */
    @PostMapping
    public Map<String, Object> createGroup(@RequestBody Group group) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证必要参数
            if (group == null) {
                result.put("code", "400");
                result.put("msg", "小组信息不能为空");
                return result;
            }
            if (group.getLeader() == null || group.getLeader().trim().isEmpty()) {
                result.put("code", "400");
                result.put("msg", "组长不能为空");
                return result;
            }
            if (group.getMembers() == null || group.getMembers().trim().isEmpty()) {
                result.put("code", "400");
                result.put("msg", "成员列表不能为空");
                return result;
            }
            
            // 确保组长在成员列表中
            String leader = group.getLeader();
            String members = group.getMembers();
            String[] memberArray = members.split(",");
            boolean leaderIncluded = false;
            
            for (String member : memberArray) {
                if (member.trim().equals(leader)) {
                    leaderIncluded = true;
                    break;
                }
            }
            
            // 如果组长不在成员列表中，将其添加到成员列表
            if (!leaderIncluded) {
                if (members.isEmpty()) {
                    members = leader;
                } else {
                    members = leader + "," + members;
                }
                group.setMembers(members);
            }
            
            // 插入新小组
            int rows = groupMapper.insertGroup(group);
            if (rows > 0) {
                result.put("code", "200");
                result.put("msg", "创建小组成功");
                result.put("data", group);
            } else {
                result.put("code", "500");
                result.put("msg", "创建小组失败");
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "创建小组失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 更新小组成员
     */
    @PutMapping("/members")
    public Map<String, Object> updateGroupMembers(@RequestParam Integer groupId, 
                                                @RequestParam String members,
                                                @RequestParam String currentUser) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证当前用户是否为小组leader
            Group group = groupMapper.getGroupById(groupId);
            if (group == null) {
                result.put("code", "404");
                result.put("msg", "小组不存在");
                return result;
            }
            
            if (!group.getLeader().equals(currentUser)) {
                result.put("code", "403");
                result.put("msg", "只有小组leader才能更新成员");
                return result;
            }
            
            // 确保组长在成员列表中
            String leader = group.getLeader();
            String[] memberArray = members.split(",");
            boolean leaderIncluded = false;
            
            for (String member : memberArray) {
                if (member.trim().equals(leader)) {
                    leaderIncluded = true;
                    break;
                }
            }
            
            // 如果组长不在成员列表中，将其添加到成员列表
            if (!leaderIncluded) {
                if (members.isEmpty()) {
                    members = leader;
                } else {
                    members = leader + "," + members;
                }
            }
            
            // 更新小组成员
            int rows = groupMapper.updateGroupMembers(groupId, members);
            if (rows > 0) {
                result.put("code", "200");
                result.put("msg", "更新小组成员成功");
            } else {
                result.put("code", "500");
                result.put("msg", "更新小组成员失败");
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "更新小组成员失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 删除小组
     */
    @DeleteMapping("/{groupId}")
    public Map<String, Object> deleteGroup(@PathVariable Integer groupId, @RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证小组是否存在
            Group group = groupMapper.getGroupById(groupId);
            if (group == null) {
                result.put("code", "404");
                result.put("msg", "小组不存在");
                return result;
            }
            
            // 验证当前用户是否为小组leader
            if (!group.getLeader().equals(username)) {
                result.put("code", "403");
                result.put("msg", "只有小组组长才能删除小组");
                return result;
            }
            
            // 删除小组
            int rows = groupMapper.deleteGroup(groupId);
            if (rows > 0) {
                result.put("code", "200");
                result.put("msg", "删除小组成功");
            } else {
                result.put("code", "500");
                result.put("msg", "删除小组失败");
            }
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "删除小组失败: " + e.getMessage());
        }
        return result;
    }
}